/**
 * Created by wangjz on 2018/11/27.
 */
import React, { Component } from 'react';
import { Layout, Menu, message } from 'antd';
import '../less/TopMenuLayout.less';
import { inject, observer } from 'mobx-react';
import RightContent from './RightContent';
import Logo from './Logo';
import { createFromIconfontCN } from '@ant-design/icons';

const Icon = createFromIconfontCN({
  scriptUrl: 'public/icon/all.js',
});
const { Header, Content } = Layout;

@inject('store')
@observer
class TopMenuLayout extends Component {

  state = {
    current: '',
  };

  /**
   * 生成菜单
   * @returns {*}
   */
  menu = () => {
    const subMenu = (children) => {
      let childrenNode = [];
      for (let item of children) {
        if (item.children) {
          childrenNode.push(<Menu.SubMenu key={item.id}
                                          title={<span>{item.icon ? <Icon type={item.icon}/> : ''} {item.name}</span>}>
            {subMenu(item.children)}
          </Menu.SubMenu>);
        } else {
          childrenNode.push(<Menu.Item key={item.id}>
            {item.icon ? <Icon type={item.icon}/> : ''} {item.name}
          </Menu.Item>);
        }
      }
      return childrenNode;
    };

    // 菜单主题
    let theme = this.props.store.getCfgValue('layout.menu.theme');
    return (
      <Menu className='top-nav'
            theme={theme}
            onSelect={this.handleClickMenu}
            selectedKeys={[this.state.current]}
            mode="horizontal">
        {subMenu(this.props.store.userInfo.moduleTree)}
      </Menu>);
  };

  /**
   * 点击菜单
   * @param item
   * @param key
   * @param keyPath
   */
  handleClickMenu = ({ item, key, keyPath }) => {
    let clickItem = this.props.store.changeUrl(key);
    if (clickItem.url == '') {
      message.success(clickItem.title + '功能未开通!', 3);
    } else {
      this.setState({ current: key });
    }
  };

  render() {
    const { store } = this.props;
    // 内容区域宽度： flow-流式， fixed - 固定宽度
    let width = store.getCfgValue('layout.top.width') == 'flow' ? '100%' : '1200px';
    // 菜单主题
    let theme = store.getCfgValue('layout.menu.theme');
    return (
      <Layout className='layout'>
        <Header className={`top-header ${theme == 'dark' ? 'backgroundDark' : 'backgroundLight'}`}>
          <div className='top-header-content' style={{ width: width }}>
            <div><Logo theme={theme}/></div>
            <div>{this.menu()}</div>
            <div><RightContent theme={theme} user={store.userInfo.user}/></div>
          </div>
        </Header>
        <Content className='top-content' style={{ width: width }}>
          <iframe src={store.currentUrl} className='top-iframe'/>
        </Content>
      </Layout>
    );
  }
}

export default TopMenuLayout;
